<template>
  <div class="labelManage" @click.self="unClick">
    <div class="tree-search-bar">
      <button class="add-btn" @click="typeOperate('add')">增加</button>
      <el-input
        v-model="filterText"
        style="width:200px"
        placeholder="输入关键字进行过滤"
        clearable
      />
    </div>
    <el-tree
      ref="tree"
      highlight-current
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false"
      :props="{
        label: 'text',
        children: 'nodes',
      }"
      :filter-node-method="filterNode"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span><svg-icon :icon-class="data.iType=='0'?'icon-wenjianyi':'icon-wenbenmoban'" /> {{ node.label }}</span>
        <span>
          <el-button plain size="mini" @click="typeOperate('edit', data)">修改</el-button>
          <el-button plain size="mini" @click="typeOperate('del', data)">删除</el-button>
        </span>
      </span>
    </el-tree>
    <input-dialog v-if="inputDialogParams.visible" ref="input-dialog" :params="inputDialogParams" />
  </div>
</template>

<script>
import { getLearnTagList, addLearnTag, setLearnTag, delLearnTag, getLearnTag } from '@/api/learnCenter'
import { arrayToTree, treeFind } from '@/utils'
import InputDialog from '@/components/Dialog/InputDialog'
export default {
  name: 'LabelManage',
  components: { InputDialog },
  data() {
    return {
      treeData: [],
      inputDialogParams: {
        visible: false
      },
      filterText: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getTypeList()
  },
  methods: {
    // 获取标签
    getTypeList() {
      const vPar = new this.ParamArr()
      getLearnTagList(vPar).then(vPar => {
        const nodes = []
        const table = new this.SQLTable(vPar.getTable('k_learn_tag'))
        table.first()
        while (!table.eof()) {
          const node = {}
          node['id'] = table.getValueByName('ID')
          node['pid'] = table.getValueByName('PID')
          node['text'] = table.getValueByName('Name')
          node['iType'] = table.getValueByName('iType')
          if (node['iType'] == '0') {
            node['icon'] = 'icon-wenjianyi'
          } else {
            node['icon'] = 'icon-wenbenmoban'
          }
          nodes.push(node)
          table.next()
        }
        this.treeData = arrayToTree(nodes, { children: 'nodes' })
      })
    },
    // 标签操作
    typeOperate(type, item) {
      let iType = 0// 1：分类 0：分组
      switch (type) {
        case 'add':
          const node = this.$refs.tree.getCurrentNode()
          this.inputDialogParams.title = '新增分类'
          this.inputDialogParams.label = '分类名称'
          this.inputDialogParams.value = ''
          if (node) {
            if (node.iType == '1') return this.$message.warning('请选择分组添加分类')
            else {
              iType = 1
            }
          } else {
            iType = 0
            this.inputDialogParams.title = '新增分组'
            this.inputDialogParams.label = '分组名称'
          }
          this.inputDialogParams.visible = true
          // 选中
          this.$nextTick(() => {
            this.$refs['input-dialog'].$refs['name0'][0].focus()
          })
          this.inputDialogParams.confirm = (form) => {
            const vPar = new this.ParamArr()
            node && vPar.setStr('PID', node.id)
            vPar.setStr('Name', form.name)
            vPar.setInt('iType', parseInt(iType)) // 1：分类 0：分组
            addLearnTag(vPar).then(vPar => {
              this.inputDialogParams.visible = false
              // 回显数据
              const p_data = {
                id: vPar.getStr('ID'),
                pid: vPar.getStr('PID'),
                text: vPar.getStr('Name'),
                iType: parseInt(iType),
                icon: vPar.getInt('iType') == 1 ? 'icon-wenbenmoban' : 'icon-wenjianyi'
              }
              if (p_data.pid) {
                this.$refs.tree.append(p_data, node.id)
              } else {
                const len = this.treeData.length
                if (len) {
                  const b_data = this.treeData[len - 1]
                  this.$refs.tree.insertAfter(p_data, b_data)
                } else {
                  this.treeData.push(p_data)
                }
              }
            })
          }
          break
        case 'edit':
          if (item.iType == '1') {
            this.inputDialogParams.title = '修改分类'
            this.inputDialogParams.label = '分类名称'
          } else {
            this.inputDialogParams.title = '修改分组'
            this.inputDialogParams.label = '分组名称'
          }
          this.inputDialogParams.value = item.text
          this.inputDialogParams.visible = true
          // 选中
          this.$nextTick(() => {
            this.$refs['input-dialog'].$refs['name0'][0].focus()
          })
          this.inputDialogParams.confirm = (form) => {
            const vPar = new this.ParamArr()
            vPar.setStr('ID', item.id)
            vPar.setStr('Name', form.name)
            setLearnTag(vPar).then(vPar => {
              this.inputDialogParams.visible = false
              // 回显数据
              const fitem = treeFind(vPar.getStr('ID'), this.treeData, { children: 'nodes' })
              fitem && (fitem.text = vPar.getStr('Name'))
            })
          }
          break
        case 'del':
          this.$comfirmDialog({
            message: `是否将“${item.text}”删除?`,
            confirm: () => {
              const vPar = new this.ParamArr()
              vPar.setStr('ID', item.id)
              delLearnTag(vPar).then(vPar => {
                this.$refs.tree.remove(vPar.getStr('ID'))
              })
            }
          })
          break
      }
    },
    // 点击外部取消树选中
    unClick() {
      this.$refs.tree.setCurrentKey(null)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.text.indexOf(value) !== -1
    }
  }
}
</script>

<style scoped lang="scss">
  .labelManage {
    width: 100%;
    padding: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .tree-search-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;
  }
  .add-btn {
    width: 96px;
    height: 30px;
    background-color: $primaryColor;
    font-size: 14px;
    color: #ffffff;
    outline: none;
    border: none;
    cursor: pointer;
  }
  ::v-deep .el-tree .el-tree-node.is-current > .el-tree-node__content {
    background: #c1e8f2;
  }
</style>
